<template>
  <div class="treehole-view">
    <div class="container">
      <div class="treehole-header">
        <h1>心灵树洞</h1>
        <p>在这里，你可以匿名分享你的心事、感受或困惑。所有内容都将严格保密。</p>
      </div>

      <!-- 弹幕区域 -->
      <div class="barrage-container" ref="barrageArea">
        <div 
          v-for="barrage in activeBarrages" 
          :key="barrage.id"
          :data-barrage-id="barrage.id"
          :class="['barrage', barrage.heat]"
          :style="barrage.style"
        >
          <div class="barrage-content">
            <i v-if="barrage.heat !== 'normal'" class="fas fa-fire fire-icon"></i>
            <span>{{ barrage.content }}</span>
          </div>
          <div class="barrage-stats">
            <button class="like-btn" @click="likeBarrage(barrage)">
              <i :class="barrage.liked ? 'fas' : 'far'" class="fa-heart"></i>
              <span class="like-count">{{ barrage.likes }}</span>
            </button>
          </div>
        </div>
      </div>

      <!-- 发布区域 -->
      <div class="treehole-form">
        <div class="form-group">
          <label for="message-title">标题（可选）</label>
          <input 
            type="text" 
            id="message-title" 
            v-model="messageTitle" 
            class="form-control" 
            placeholder="给倾诉起个标题..."
          >
        </div>
        
        <div class="form-group">
          <label for="message-content">倾诉内容</label>
          <textarea 
            id="message-content" 
            v-model="messageContent" 
            class="form-control" 
            placeholder="写下你的心事、感受或困惑..."
            rows="6"
          ></textarea>
        </div>
        
        <div class="form-group">
          <label for="message-mood">当前心情</label>
          <div class="mood-selector">
            <button 
              v-for="mood in moods" 
              :key="mood.value"
              :class="['mood-btn', { active: selectedMood === mood.value }]"
              @click="selectMood(mood.value)"
              :title="mood.label"
            >
              <i :class="mood.icon"></i>
            </button>
          </div>
        </div>
        
        <button class="submit-btn" @click="submitMessage">
          <i class="fas fa-paper-plane"></i> 匿名分享
        </button>
        
        <p class="confidentiality">
          <i class="fas fa-lock"></i> 所有内容将严格保密，不会收集任何个人信息
        </p>
      </div>

      <!-- 消息列表 -->
      <div class="treehole-messages">
        <div class="messages-header">
          <h2>最近倾诉</h2>
          <div class="messages-filter">
            <button 
              v-for="filter in filters" 
              :key="filter.value"
              :class="['filter-btn', { active: currentFilter === filter.value }]"
              @click="setFilter(filter.value)"
            >
              {{ filter.label }}
            </button>
          </div>
        </div>
        
        <div class="messages-grid">
          <div v-for="message in filteredMessages" :key="message.id" class="message-card">
            <div class="message-header">
              <span class="message-mood">
                <i :class="message.mood.icon"></i>
              </span>
              <span class="message-date">{{ message.date }}</span>
            </div>
            
            <div class="message-content">
              <h3 v-if="message.title">{{ message.title }}</h3>
              <p>{{ message.content }}</p>
            </div>
            
            <div class="message-actions">
              <button class="action-btn" @click="supportMessage(message)">
                <i class="fas fa-heart"></i> 支持 <span>({{ message.supportCount }})</span>
              </button>
              <button class="action-btn" @click="shareMessage(message)">
                <i class="fas fa-share-alt"></i> 分享
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'TreeholeView',
  data() {
    return {
      messageTitle: '',
      messageContent: '',
      selectedMood: 'neutral',
      currentFilter: 'all',
      moods: [
        { value: 'happy', label: '开心', icon: 'fas fa-smile' },
        { value: 'neutral', label: '平静', icon: 'fas fa-meh' },
        { value: 'sad', label: '难过', icon: 'fas fa-sad-tear' },
        { value: 'angry', label: '生气', icon: 'fas fa-angry' },
        { value: 'love', label: '心动', icon: 'fas fa-heart' }
      ],
      filters: [
        { value: 'all', label: '全部' },
        { value: 'recent', label: '最新' },
        { value: 'popular', label: '最热' }
      ],
      messages: [
        {
          id: 1,
          title: '工作压力好大',
          content: '最近工作压力好大，感觉每天都在被deadline追赶。今天加班到深夜，回到家连说话的力气都没有了。不知道这样的日子还要持续多久...',
          date: '昨天 22:34',
          mood: { value: 'sad', icon: 'fas fa-sad-tear' },
          supportCount: 12
        },
        {
          id: 2,
          title: '表白被拒了',
          content: '今天鼓起勇气向喜欢的人表白了！虽然被拒绝了，但反而感觉轻松了。至少没有遗憾了，继续向前看！',
          date: '2天前',
          mood: { value: 'neutral', icon: 'fas fa-meh' },
          supportCount: 42
        },
        {
          id: 3,
          title: '毕业五年了',
          content: '毕业五年了，感觉离自己当初的梦想越来越远。每天做着不喜欢的工作，只是为了生存。该不该放弃一切重新开始？',
          date: '3天前',
          mood: { value: 'sad', icon: 'fas fa-sad-tear' },
          supportCount: 27
        },
        {
          id: 4,
          title: '今天很开心',
          content: '今天收到了期待已久的offer！终于可以开始新的工作了，希望这是一个好的开始！',
          date: '4天前',
          mood: { value: 'happy', icon: 'fas fa-smile' },
          supportCount: 35
        }
      ],
      // 弹幕相关数据
      activeBarrages: [],
      barrageInterval: null,
      barrageIdCounter: 0,
      sampleBarrages: [
        { content: "今天鼓起勇气向喜欢的人表白了！虽然被拒绝了，但反而感觉轻松了", likes: 42, heat: "hot" },
        { content: "工作压力好大，每天都在被deadline追赶，不知道这样的日子还要持续多久", likes: 18, heat: "normal" },
        { content: "毕业五年了，感觉离自己当初的梦想越来越远。该不该放弃一切重新开始？", likes: 27, heat: "normal" },
        { content: "今天收到了心仪公司的offer！努力终于有了回报，开心！", likes: 65, heat: "fire" },
        { content: "一个人在大城市打拼，有时候真的很孤独", likes: 35, heat: "hot" },
        { content: "坚持健身三个月了，感觉整个人都焕然一新！", likes: 58, heat: "fire" },
        { content: "和父母发生了争执，明明知道他们是为我好，但还是控制不住情绪", likes: 22, heat: "normal" },
        { content: "最近开始学习烹饪，发现自己还挺有天赋的~", likes: 31, heat: "hot" },
        { content: "养了一只小猫，每天回家都有个小生命在等我，感觉太治愈了", likes: 72, heat: "fire" },
        { content: "连续加班两周了，今天终于可以好好休息一下", likes: 15, heat: "normal" },
        { content: "读了一本改变人生的书，强烈推荐《被讨厌的勇气》", likes: 38, heat: "hot" },
        { content: "今天帮助了一位陌生人，看到对方感激的笑容，心里暖暖的", likes: 47, heat: "fire" },
        { content: "坚持写日记100天了，看着自己的成长轨迹感觉很棒", likes: 29, heat: "normal" }
      ]
    }
  },
  computed: {
    filteredMessages() {
      let filtered = [...this.messages];
      
      switch (this.currentFilter) {
        case 'recent':
          filtered.sort((a, b) => new Date(b.date) - new Date(a.date));
          break;
        case 'popular':
          filtered.sort((a, b) => b.supportCount - a.supportCount);
          break;
      }
      
      return filtered;
    }
  },
  methods: {
    selectMood(mood) {
      this.selectedMood = mood;
    },
    setFilter(filter) {
      this.currentFilter = filter;
    },
    submitMessage() {
      if (!this.messageContent.trim()) {
        alert('请填写倾诉内容');
        return;
      }
      
      const selectedMoodObj = this.moods.find(m => m.value === this.selectedMood);
      
      // 创建新消息
      const newMessage = {
        id: this.messages.length + 1,
        title: this.messageTitle.trim(),
        content: this.messageContent.trim(),
        date: '刚刚',
        mood: selectedMoodObj,
        supportCount: 0
      };
      
      // 添加到消息列表
      this.messages.unshift(newMessage);
      
      // 创建新弹幕
      this.createBarrage(this.messageContent.trim());
      
      // 清空表单
      this.messageTitle = '';
      this.messageContent = '';
      this.selectedMood = 'neutral';
      
      // 提示成功
      alert('倾诉已提交！(实际发送功能待实现)');
    },
    supportMessage(message) {
      message.supportCount++;
    },
    shareMessage(message) {
      // 创建分享文本
      const shareText = message.title 
        ? `${message.title}\n\n${message.content}`
        : message.content;
      
      // 复制到剪贴板
      navigator.clipboard.writeText(shareText)
        .then(() => alert('内容已复制到剪贴板，可以分享给朋友了'))
        .catch(err => console.error('复制失败:', err));
    },
    // 弹幕相关方法
    createBarrage(content, likes = 0, heat = 'normal') {
      // Generate a unique ID for the barrage
      const barrageId = `barrage-${this.barrageIdCounter++}`; // Ensure unique ID format

      const containerHeight = this.$refs.barrageArea.clientHeight;
      const trackHeight = containerHeight / 5;
      const track = Math.floor(Math.random() * 5);
      // Ensure barrage stays within bounds
      const top = track * trackHeight + Math.random() * (trackHeight - 60); // Adjusted for padding/icons
      
      const newBarrage = {
        id: barrageId,
        content,
        likes,
        heat,
        liked: false,
        // Initial position is off-screen right
        style: {
          top: `${top}px`,
          // Start off screen right, will be animated later
          transform: `translateX(${window.innerWidth}px)`
        }
      };
      
      this.activeBarrages.push(newBarrage);
      
      // Wait for Vue to render the new element, then attempt to animate it
      this.$nextTick(() => {
        // Use a more specific and potentially delayed query for the element
        const attemptAnimation = () => {
          const specificBarrageElement = this.$refs.barrageArea.querySelector(`[data-barrage-id="${barrageId}"]`);
          
          if (specificBarrageElement) {
            console.log(`Element found for barrage ${barrageId}, attempting animation.`);
             // Use Web Animations API for smooth animation
            const duration = 15000 + Math.random() * 20000;
            
            specificBarrageElement.animate(
              [
                { transform: `translateX(${window.innerWidth}px)` }, // Start from initial off-screen position
                { transform: 'translateX(-100%)' } // Move left by 100% of its own width
              ],
              {
                duration: duration,
                easing: 'linear'
              }
            ).onfinish = () => {
              console.log(`Animation finished for barrage ${barrageId}, removing.`);
              // Remove the barrage from the activeBarrages array after animation
              const index = this.activeBarrages.findIndex(b => b.id === barrageId);
              if (index > -1) {
                this.activeBarrages.splice(index, 1);
              }
            };
          } else {
            console.warn(`Element not found for barrage ${barrageId} immediately, retrying...`);
            // If element not found, wait a bit and try again (with a limit to prevent infinite loops)
            // For simplicity here, we'll just log and let it go, but in a real app, you'd add retry logic.
            // Let's add a fallback removal though.
             setTimeout(() => {
                const index = this.activeBarrages.findIndex(b => b.id === barrageId);
                  if (index > -1) {
                    console.warn(`Element for barrage ${barrageId} still not found, removing as fallback.`);
                    this.activeBarrages.splice(index, 1);
                  }
             }, 5000 + Math.random() * 5000); // Remove after a few seconds if animation couldn't start
          }
        };

        // Call the animation attempt function after a very small delay to ensure browser paint
        setTimeout(attemptAnimation, 20);
      });
    },
    likeBarrage(barrage) {
      if (!barrage.liked) {
         barrage.likes++;
         barrage.liked = true;
      }
    },
    initBarrages() {
      this.sampleBarrages.forEach(barrage => {
        this.createBarrage(barrage.content, barrage.likes, barrage.heat);
      });
      
      this.barrageInterval = setInterval(() => {
        const randomIndex = Math.floor(Math.random() * this.sampleBarrages.length);
        const randomBarrage = this.sampleBarrages[randomIndex];
        this.createBarrage(randomBarrage.content, randomBarrage.likes, randomBarrage.heat);
      }, 5000);
    }
  },
  mounted() {
    // Wait for the component to be mounted and the DOM to be ready
    this.$nextTick(() => {
       // Ensure the barrage area has a clientHeight before initializing
       // Add a small delay to give the container time to render with correct dimensions
       setTimeout(() => {
         if (this.$refs.barrageArea && this.$refs.barrageArea.clientHeight > 0) {
           this.initBarrages();
         } else {
            console.error("Barrage area clientHeight is still 0 after delay. Barrage initialization skipped.");
         }
       }, 50); // Small delay added
    });
  },
  beforeUnmount() {
    if (this.barrageInterval) {
      clearInterval(this.barrageInterval);
    }
  }
}
</script>

<style scoped>
.treehole-view {
  padding: 60px 0;
}

.container {
  max-width: 900px;
  margin: 0 auto;
  padding: 0 20px;
}

.treehole-header {
  text-align: center;
  margin-bottom: 40px;
}

.treehole-header h1 {
  font-size: 2.5em; /* Larger heading */
  margin-bottom: 15px;
  color: var(--primary-color);
}

.treehole-header p {
  color: var(--text-light);
  max-width: 600px;
  margin: 0 auto;
  font-size: 1.1em;
}

/* 弹幕容器 */
.barrage-container {
  position: relative;
  width: 100%;
  height: 400px;
  background: var(--card-bg);
  border: 1px solid var(--border-color);
  border-radius: 15px;
  overflow: hidden;
  box-shadow: var(--shadow);
  backdrop-filter: blur(5px);
  -webkit-backdrop-filter: blur(5px);
  z-index: 1;
  pointer-events: none; /* Allow clicks to pass through */
  margin: 20px 0 40px 0;
}

/* 弹幕样式 */
.barrage {
  position: absolute;
  white-space: nowrap;
  font-size: 1em;
  padding: 8px 15px; /* Adjusted padding */
  border-radius: 20px; /* More rounded */
  background: rgba(var(--primary-color-rgb), 0.1); /* Use primary color with alpha */
  border: 1px solid rgba(var(--primary-color-rgb), 0.3);
  color: var(--text-color);
  box-shadow: var(--shadow);
  transition: all 0.3s ease;
  cursor: pointer;
  display: flex;
  align-items: center;
  z-index: 5;
  pointer-events: auto; /* Re-enable clicks on the barrage itself */
}

.barrage:hover {
  transform: scale(1.05);
  box-shadow: 0 0 20px rgba(var(--primary-color-rgb), 0.4); /* Use primary color for hover glow */
}

.barrage-content {
  margin-right: 10px; /* Adjusted margin */
  max-width: 500px;
  overflow: hidden;
  text-overflow: ellipsis;
  color: var(--text-color);
}

.barrage-stats {
  display: flex;
  align-items: center;
}

.like-btn {
  background: none;
  border: none;
  color: var(--text-light); /* Use text-light for default */
  cursor: pointer;
  font-size: 0.9em; /* Adjusted font size */
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 5px;
  padding: 0;
}

.like-btn:hover {
  color: var(--accent-color); /* Use accent color for hover */
}

.like-btn .fa-heart.fas {
    color: var(--accent-color); /* Use accent color for filled heart */
}

.like-count {
  font-size: 0.9em; /* Adjusted font size */
  color: var(--text-light);
}

/* 弹幕热度状态 */
.barrage.normal {
  /* defaults are set in .barrage */
}

.barrage.hot {
  border: 1px solid rgba(var(--warning-color-rgb), 0.5); /* Use warning color */
  background: rgba(var(--warning-color-rgb), 0.1);
  color: var(--warning-color); /* Use warning color */
}

.barrage.hot .fire-icon {
  color: var(--warning-color); /* Use warning color */
  margin-right: 8px; /* Adjusted margin */
  animation: flame 1.5s infinite alternate;
}

.barrage.fire {
  border: 1px solid rgba(var(--error-color-rgb), 0.7); /* Use error color */
  background: rgba(var(--error-color-rgb), 0.15);
  font-weight: 500;
  padding: 10px 20px; /* Adjusted padding */
  color: var(--error-color); /* Use error color */
}

.barrage.fire .fire-icon {
  color: var(--error-color); /* Use error color */
  margin-right: 10px; /* Adjusted margin */
  animation: bigFlame 1s infinite alternate;
}

@keyframes flame {
  0% { opacity: 0.7; transform: scale(1); }
  100% { opacity: 1; transform: scale(1.1); }
}

@keyframes bigFlame {
  0% { opacity: 0.8; transform: scale(1); } /* Adjusted opacity */
  50% { transform: scale(1.2); } /* Adjusted scale */
  100% { opacity: 1; transform: scale(1.1); } /* Adjusted scale */
}

/* Note: moveLeft keyframes are not needed if using Web Animations API */
/* @keyframes moveLeft {
  from { transform: translateX(100vw); }
  to { transform: translateX(-100%); }
} */

.treehole-form {
  max-width: 800px;
  margin: 0 auto 60px;
  background: var(--card-bg);
  padding: 30px;
  border-radius: 15px;
  box-shadow: var(--shadow);
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: var(--text-color);
}

.form-control {
  width: 100%;
  padding: 12px;
  border: 1px solid var(--border-color); /* Use variable */
  border-radius: 8px;
  font-family: inherit;
  font-size: 1rem;
  transition: var(--transition);
  background: var(--bg-color-light); /* Use variable */
  color: var(--text-color);
}

/* dark-mode specific form-control style removed, rely on variables */
/* .dark-mode .form-control {
  border-color: #444;
  background: #333;
  color: #eee;
} */

.form-control:focus {
  border-color: var(--primary-color);
  outline: none;
  box-shadow: 0 0 0 3px rgba(var(--primary-color-rgb), 0.2); /* Use variable */
}

.mood-selector {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.mood-btn {
  width: 40px;
  height: 40px;
  border: 1px solid var(--border-color); /* Added border */
  border-radius: 50%;
  background: var(--bg-color-light); /* Use variable */
  color: var(--text-color); /* Use variable */
  font-size: 20px;
  cursor: pointer;
  transition: var(--transition);
  display: flex;
  justify-content: center;
  align-items: center;
}

.mood-btn:hover {
  transform: translateY(-2px);
  border-color: var(--primary-color); /* Highlight on hover */
}

.mood-btn.active {
  background: var(--primary-color);
  color: white;
  border-color: var(--primary-color); /* Ensure border matches */
}

.submit-btn {
  background: var(--primary-color);
  color: white;
  border: none;
  padding: 12px 30px;
  border-radius: 30px;
  font-size: 1rem;
  font-weight: 500;
  cursor: pointer;
  transition: var(--transition);
  display: flex;
  align-items: center;
  gap: 8px;
  margin: 0 auto;
}

.submit-btn:hover {
  background: var(--secondary-color);
  transform: translateY(-2px);
}

.confidentiality {
  text-align: center;
  font-size: 0.9em;
  color: var(--text-light);
  margin-top: 20px;
}

.confidentiality i {
  margin-right: 5px;
}

.messages-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  flex-wrap: wrap;
  gap: 15px;
}

.messages-header h2 {
  font-size: 24px;
  color: var(--text-color);
}

.messages-filter {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.filter-btn {
  padding: 8px 15px; /* Adjusted padding */
  border: 1px solid var(--border-color); /* Added border */
  border-radius: 20px;
  background: var(--card-bg);
  color: var(--text-color);
  cursor: pointer;
  transition: var(--transition);
}

.filter-btn:hover {
  background: var(--primary-color);
  color: white;
  border-color: var(--primary-color); /* Highlight on hover */
}

.filter-btn.active {
  background: var(--primary-color);
  color: white;
  border-color: var(--primary-color); /* Ensure border matches */
}

.messages-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
}

.message-card {
  background: var(--card-bg);
  border-radius: 15px;
  padding: 20px;
  box-shadow: var(--shadow);
  transition: var(--transition);
  display: flex;
  flex-direction: column;
  border: 1px solid var(--border-color); /* Added border */
}

.message-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 12px 20px rgba(0, 0, 0, 0.15); /* Enhanced hover shadow */
}

.message-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.message-mood {
  font-size: 24px;
  color: var(--primary-color);
}

.message-date {
  font-size: 14px;
  color: var(--text-light);
}

.message-content {
  margin-bottom: 20px;
  flex-grow: 1;
}

.message-content h3 {
  font-size: 1.2em; /* Adjusted font size */
  margin-bottom: 10px;
  color: var(--text-color);
}

.message-content p {
  color: var(--text-color); /* Use text-color for content */
  line-height: 1.6;
  word-break: break-word;
}

.message-actions {
  display: flex;
  gap: 15px; /* Adjusted gap */
  margin-top: auto;
}

.action-btn {
  background: none;
  border: none;
  color: var(--text-light);
  cursor: pointer;
  font-size: 1em; /* Adjusted font size */
  transition: var(--transition);
  display: flex;
  align-items: center;
  gap: 5px;
  padding: 0;
}

.action-btn:hover {
  color: var(--primary-color);
}

@media (max-width: 768px) {
  .treehole-view {
    padding: 40px 15px; /* Adjusted padding */
  }

  .treehole-header {
    margin-bottom: 30px;
  }

  .treehole-header h1 {
    font-size: 2em;
  }

  .treehole-header p {
    font-size: 1em;
  }

  .barrage-container {
    height: 300px;
    margin-bottom: 30px; /* Adjusted margin */
  }

  .barrage {
    font-size: 0.9em; /* Adjusted font size */
    padding: 6px 12px; /* Adjusted padding */
  }

  .treehole-form {
    padding: 20px;
    margin-bottom: 40px;
  }

  .form-group label {
    font-size: 1em; /* Adjusted font size */
  }

  .form-control {
    padding: 10px;
    font-size: 0.9em; /* Adjusted font size */
  }

  textarea.form-control {
    min-height: 120px;
  }

  .mood-selector {
    justify-content: center;
    gap: 8px; /* Adjusted gap */
  }

  .mood-btn {
    width: 35px;
    height: 35px;
    font-size: 18px; /* Adjusted font size */
  }

  .submit-btn {
    padding: 10px 25px;
    font-size: 1em; /* Adjusted font size */
  }

  .messages-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }

  .messages-header h2 {
    font-size: 20px;
  }

  .messages-filter {
    width: 100%;
    justify-content: center;
    gap: 8px; /* Adjusted gap */
  }

  .filter-btn {
     padding: 6px 12px; /* Adjusted padding */
     font-size: 0.9em; /* Adjusted font size */
  }

  .messages-grid {
    grid-template-columns: 1fr;
    gap: 15px; /* Adjusted gap */
  }

  .message-card {
    padding: 15px;
  }

  .message-content h3 {
    font-size: 1.1em; /* Adjusted font size */
  }

  .message-content p {
    font-size: 0.9em; /* Adjusted font size */
  }

  .message-actions {
    gap: 10px; /* Adjusted gap */
  }
}
</style> 